package timesheet.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import timesheet.model.Badging;
import timesheet.model.Users;
import timesheet.repository.BadgingRepository;
import timesheet.repository.UserRepository;
import timesheet.web.ContextUtil;

@Controller
@Transactional
public class BadgingController {
	
	@Autowired UserRepository userRepository;
	@Autowired BadgingRepository badgingRepository;
	
	@RequestMapping("/index")
	public String badgingcontroller(){
		if((Long)ContextUtil.getHttpSession().getAttribute("UserId")==null)
			return "home";
		else return "index";
		}
	
	//use badging entity to save start and stop time
	@RequestMapping("/startday")
	public ModelAndView startday(){
		if((Long)ContextUtil.getHttpSession().getAttribute("UserId")!=null){
			HttpSession session = ContextUtil.getHttpSession();
			Boolean start = true;
			Boolean stop = false;
			session.setAttribute("STARTDAY", start);
			session.setAttribute("STOPDAY", stop);
			Long userId = (Long)session.getAttribute("UserId");
			Users u = userRepository.find(userId);
			Badging b = new Badging();
			b.setStart(new Date());
			b.setU(u);
			badgingRepository.merge(b);
			return new ModelAndView("index");
		}
		else{
			return new ModelAndView("home");
		}
	}
	
	@RequestMapping("/stopday")
	public ModelAndView stopday(){
		if((Long)ContextUtil.getHttpSession().getAttribute("UserId")!=null){
			HttpSession session = ContextUtil.getHttpSession();
			Boolean start = false;
			Boolean stop = true;
			session.setAttribute("STARTDAY", start);
			session.setAttribute("STOPDAY", stop);
			Long userId = (Long)session.getAttribute("UserId");
			Users u = userRepository.find(userId);
			if(badgingRepository.getLastBadgingTimeByUser(u) != null){
				Badging b = badgingRepository.getLastBadgingTimeByUser(u);
				b.setStop(new Date());
				long interval = ((b.getStop().getTime()) - (b.getStart().getTime()))/1000;
				b.setInterval(interval);
			}
			return new ModelAndView("index");
		}
		else{
			return new ModelAndView("home");
		}
	}
}
